import debounce from 'lodash.debounce';
import React  from 'react';
import PropTypes from 'proptypes';
import Draggable from 'react-draggable';
// import cloneDeep from 'lodash.clonedeep';
import TableCell from './query-result-table-cell.jsx';
import PreviewModal from './preview-modal.jsx';
import { valueToString } from '../utils/convert';
// import scrollbarSize from 'dom-helpers/util/scrollbarSize';
import EditModal from './EditModal';
import SaveIcon from '@mui/icons-material/Save'
import FileCopyIcon from '@mui/icons-material/FileCopy'

import GridOnIcon from '@mui/icons-material/GridOn'
// import 'react-virtualized/styles.css';
// import './query-result-table.scss';
import Button from '@mui/material/Button';
// import IconButton from '@mui/material/IconButton';

/* eslint react/sort-comp:0 */
export default function QueryResultTable(props){
  // static propTypes = {
  //   widthOffset: PropTypes.number.isRequired,
  //   heigthOffset: PropTypes.number.isRequired,
  //   onCopyToClipboardClick: PropTypes.func.isRequired,
  //   onSaveToFileClick: PropTypes.func.isRequired,
  //   resultItemsPerPage: PropTypes.number.isRequired,
  //   copied: PropTypes.bool,
  //   saved: PropTypes.bool,
  //   query: PropTypes.string,
  //   fields: PropTypes.array,
  //   rows: PropTypes.array,
  //   cellClass: PropTypes.string,
  //   nullCellClass: PropTypes.string,
  //   rowCount: PropTypes.oneOfType([PropTypes.array, PropTypes.number]),
  // };

    const [state,setState]=React.useState({
      columnWidths: {},
      autoColumnWidths: [],
      showPreview: false,
      showEdit: false,
      pos: null,
    });
    // const resizeHandler = debounce(onResize, 20);
  
  // React.useEffect(()=>{
  //   window.addEventListener('resize', resizeHandler, false);
  //   resize();
       // return(()=>{
       //    window.removeEventListener('resize', resizeHandler, false);    
       // })
  // },[]);
    // console.log("UNSAFE_componentWillReceiveProps");
    // console.log(nextProps);

  React.useEffect(()=>{
    setState((state)=>({...state, showCopied: true }));
    setTimeout(() => setState((state)=>({...state, showCopied: false })), 3000);
  },[props.copied])
  React.useEffect(()=>{
    setState((state)=>({...state, showSaved: true }));
    setTimeout(() =>{setState((state)=>({...state, showSaved: false }));}, 3000);
  },[props.saved])


  const onColumnResizeEndCallback=(newColumnWidth, columnKey)=> {
    setState(({ columnWidths }) => ({
      columnWidths: {
        ...columnWidths,
        [columnKey]: newColumnWidth,
      },
    }));
  }

  const onOpenPreviewClick = value => {
    setState({ showPreview: true, valuePreview: value });
  };
  const onEditClick = (row, col) => {
    console.log(row + ',' + col);
    console.log(this);

    setState({ showEdit: true, pos: { row: row, col: col } });
  };
  const onClosePreviewClick = () => {
    setState({ showPreview: false, valuePreview: null });
  };
  const onCloseEditClick = () => {
    setState({ showEdit: false, pos: null });
  };
  const onResize=()=> {
    clearTimeout(resizeTimer);
    resizeTimer = setTimeout(resize, 16);
  }

  const getTextWidth=(text, font) =>{
    // additional spacing
    const padding = 28;
    const element = document.createElement('canvas');
    const context = element.getContext('2d');
    context.font = font;
    return context.measureText(text).width + padding;
  }

  // const autoResizeColumnsWidth(fields, rows, tableWidth) {
  //   // console.log("autoResizeColumnsWidth");
  //   const averageTableCellWidth = tableWidth / fields.length;
  //   let totalColumnWidths = 0;

  //   const autoColumnWidths = fields.map((name, index) => {
  //     const cellWidth = resolveCellWidth(
  //       name,
  //       fields,
  //       rows,
  //       averageTableCellWidth
  //     );
  //     totalColumnWidths = totalColumnWidths + cellWidth;

  //     const isLastColumn = index + 1 === fields.length;
  //     if (isLastColumn && totalColumnWidths < tableWidth) {
  //       totalColumnWidths = totalColumnWidths - cellWidth;
  //       return tableWidth - totalColumnWidths;
  //     }

  //     return cellWidth;
  //   });

  //   setState({ autoColumnWidths });
  // }

  // const renderHeaderCell(params) {
  //   const field = props.fields[params.columnIndex];
  //   const handleStop = handleStop.bind(this, {
  //     name: field.name,
  //     index: params.columnIndex,
  //   });

  //   // We don't want the resizable handle on the last column for layout reasons
  //   let resizeDrag = null;
  //   if (props.fields.length - 1 !== params.columnIndex) {
  //     resizeDrag = (
  //       <Draggable
  //         axis="x"
  //         onStop={handleStop}
  //         position={{ x: 0, y: 0 }}
  //         zIndex={999}
  //       >
  //         <div className="draggable-handle" />
  //       </Draggable>
  //     );
  //   }
  //   // var style=cloneDeep(params.style);
  //   // style.backgroundClip="border-box";
  //   // style.display="block";
  //   // style.lineHeight="20px"
  //   // style.overflow="hidden";
  //   return (
  //     <span style={params.style} key={params.key} className="cell">
  //       <strong>{field.name}</strong>
  //       {resizeDrag}
  //     </span>
  //   );
  // }

  const renderNoRows=()=> {
    return (
      <div style={{ textAlign: 'center', fontSize: '16px' }}>
        No results found
      </div>
    );
  }

  const handleStop=(data, e, move)=> {
    const { columnWidths } = state;
    const originalWidth = getColumnWidth(data);

    // update dragged column width
    setState({
      columnWidths: {
        ...columnWidths,
        [data.name]: Math.max(originalWidth + move.x, 10),
      },
    });

    if (headerdiv) {
      headerdiv.measureAllCells();
      headerdiv.recomputedivSize();
      headerdiv.forceUpdate();
    }

    if (rowsdiv) {
      rowsdiv.measureAllCells();
      rowsdiv.recomputedivSize();
      rowsdiv.forceUpdate();
    }
  }

  // const resize(nextProps) {
  //   // console.log("============table resize");

  //   const props = nextProps || props;
  //   let tableWidth;
  //   //if(props.collapseV){
  //   // console.log(props.widthOffset);

  //   tableWidth = window.innerWidth - (props.widthOffset + 27 + 2 + 3 + 2);
  //   // console.log(props.heigthOffset);

  //   let tableHeight = window.innerHeight - (props.heigthOffset + 225);
  //   if (tableHeight < 300) tableHeight = 300;
  //   // trigger columns resize
  //   autoResizeColumnsWidth(props.fields, props.rows, tableWidth);

  //   setState({ tableWidth, tableHeight });
  // }

  const renderHeaderTopBar=()=> {
    const {
      rows,
      rowCount,
      onCopyToClipboardClick,
      onSaveToFileClick,
    } = props;
    // const styleCopied = {
    //   display: state.showCopied ? 'inline-block' : 'none',
    // };
    // const styleSaved = {
    //   display: state.showSaved ? 'inline-block' : 'none',
    // };
    // const styleCopyButtons = {
    //   display: state.showCopied ? 'none' : 'inline-block',
    // };
    // const styleSaveButtons = {
    //   display: state.showSaved ? 'none' : 'inline-block',
    // };

    let copyPanel = null;
    let savePanel = null;
    if (rowCount) {
      copyPanel = (
        <div
          className="ui small label"
          title="Copy as"
          style={{ float: 'right', margin: '3px' }}
        >
          <FileCopyIcon />
          <Button
            className="detail"
            onClick={() => onCopyToClipboardClick(rows, 'CSV')}
          >
            CSV
          </Button>
          <Button
            className="detail"
            onClick={() => onCopyToClipboardClick(rows, 'JSON')}
          >
            JSON
          </Button>
        </div>
      );

      savePanel = (
        <div
          className="ui small label"
          title="Save as"
          style={{ float: 'right', margin: '3px' }}
        >
          <SaveIcon />
          <Button
            className="detail"
            onClick={() => onSaveToFileClick(rows, 'CSV')}
          >
            CSV
          </Button>
          <Button
            className="detail"
            onClick={() => onSaveToFileClick(rows, 'JSON')}
          >
            JSON
          </Button>
        </div>
      );
    }

    return (
      <div style={{ background: 'rgba(0, 0, 0, 0.05)', overflow: 'hidden' }}>
        <div className="ui label" style={{ margin: '3px', float: 'left' }}>
          <GridOnIcon />
          Rows
          <div className="detail">{rowCount}</div>
        </div>
        {savePanel}
        {copyPanel}
      </div>
    );
  }
  const renderEditModal=()=> {
    if (!state.showEdit) {
      return null;
    }

    return (
      <EditModal
        modalOpen={state.showEdit}
        pos={state.pos}
        onCloseClick={onCloseEditClick}
      />
    );
  }
  const renderPreviewModal=()=> {
    if (!state.showPreview) {
      return null;
    }

    return (
      <PreviewModal
        modalOpen={state.showPreview}
        value={state.valuePreview}
        onCloseClick={onClosePreviewClick}
      />
    );
  }

  const renderTableBody=(onScroll)=> {
    const { rowCount, fields } = props;
    const { tableWidth, tableHeight } = state;

    const headerHeight = 62; // value of 2 headers together
    const scrollBarHeight = 15;
    const rowHeight = 28;
    const fixedHeightRows = (rowCount || 1) * rowHeight + scrollBarHeight;
    let view_rows=props.rows.map((item,idx)=>{
      let view_fields=fields.map((field,idx2)=>
        (
      <TableCell
        key={idx2}
        rowIndex={idx}
        data={props.rows}
        col={field.name}
        onOpenPreviewClick={onOpenPreviewClick}
        onDeleteClick={() => {
          console.log('delete');
          // console.log(props.rows[idx]);
          props.onDeleteClick(props.rows[idx])
        }}
        onEditClick={() => {
          console.log('edit');
        }}
      />
        ));
      return <tr key={idx}>{view_fields}</tr>  
    });
    return(view_rows)
    return (
      <div
        className="div-body"
        ref={ref => {
          rowsdiv = ref;
        }}
        cellRenderer={renderCell}
        width={tableWidth}
        height={Math.min(tableHeight - headerHeight, fixedHeightRows)}
        rowHeight={rowHeight}
        onScroll={onScroll}
        rowCount={rowCount}
        columnCount={fields.length}
        columnWidth={getColumnWidth}
        rowsCount={rowCount}
        noContentRenderer={renderNoRows}
      />
    );
  }

  const renderTableHeader=(scrollLeft) =>{
    const { fields } = props;
    const { tableWidth } = state;

    if (!fields.length) {
      return null;
    }
    let view_fields=fields.map((item,idx)=>(<td key={idx}>{item.name}</td>));
    return(<tr>{view_fields}</tr>)
    return (
      <div
        ref={ref => {
          headerdiv = ref;
        }}
        columnWidth={getColumnWidth}
        columnCount={fields.length}
        height={30}
        cellRenderer={renderHeaderCell}
        className={'Headerdiv'}
        rowHeight={30}
        rowCount={1}
        getScrollbarSize={() => {
          return 0;
        }}
        width={tableWidth - scrollbarSize()}
        scrollLeft={scrollLeft}
      />
    );
  }

  // const getColumnWidth({ index }) {
  //   const { columnWidths, autoColumnWidths } = state;
  //   const field = props.fields[index];

  //   if (field && columnWidths && columnWidths[field.name] !== undefined) {
  //     return columnWidths[field.name];
  //   } else if (autoColumnWidths && autoColumnWidths[index] !== undefined) {
  //     return autoColumnWidths[index];
  //   }
  //   return 50;
  // }

  /**
   * Resolve the cell width based in the header name and the top 30 rows data.
   * It gives a better UX since the column adapts better to the table width.
   */
  // const resolveCellWidth(fieldName, fields, rows) {
  //   const font = "14px 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif";
  //   const numRowsToFindAverage = rows.length > 30 ? 30 : rows.length;
  //   const maxWidth = 220;

  //   const headerWidth = getTextWidth(fieldName, `bold ${font}`);

  //   let averageRowsCellWidth = 0;
  //   if (rows.length) {
  //     averageRowsCellWidth =
  //       rows
  //         .slice(0, numRowsToFindAverage)
  //         .map(row => {
  //           const value = valueToString(row[fieldName]);
  //           return getTextWidth(value, font);
  //         })
  //         .reduce((prev, curr) => prev + curr, 0) / numRowsToFindAverage;
  //   }

  //   if (headerWidth > averageRowsCellWidth) {
  //     return headerWidth > maxWidth ? maxWidth : headerWidth;
  //   }

  //   return averageRowsCellWidth > maxWidth ? maxWidth : averageRowsCellWidth;
  // }

  // const renderCell(params) {
  //   const field = props.fields[params.columnIndex];
  //   return (
  //     <TableCell
  //       style={params.style}
  //       key={params.key}
  //       rowIndex={params.rowIndex}
  //       data={props.rows}
  //       col={field.name}
  //       onOpenPreviewClick={onOpenPreviewClick}
  //       onDeleteClick={() => {
  //         window.model = props.model;
  //         console.log(props.model);
  //         console.log(props.model.store.columns.columnsByTable);
  //         console.log('delete');
  //       }}
  //       onEditClick={() => {
  //         console.log('edit');
  //       }}
  //     />
  //   );
  // }

    // not completed loaded yet
    // if (!state.tableWidth) {
    //   return null;
    // }

    return (
      <div>
        {renderPreviewModal()}
        {renderEditModal()}
        <div>
            <div className="div-query-wrapper">
              {renderHeaderTopBar()}
              <table border="1">
              <thead>
              {renderTableHeader()}
              </thead>
              <tbody>
              {renderTableBody()}
              </tbody>
              </table>
            </div>
        </div>
      </div>
    );
  }
// react-dom.development.js:67 Warning: Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.